package com.tour.controller;

import com.tour.bean.ReturnT;
import com.tour.service.IndexService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @ClassName IndexController
 * @Author 张梦兴
 * @Date 2020/3/13 16:01
 * @describe 加载首页数据
 */
@RestController
@RequestMapping("index")
public class IndexController {

    private final Logger log=Logger.getLogger(IndexController.class);

    @Autowired
    private IndexService service;

    @RequestMapping("/load")
    public ReturnT<Map> loadIndex(){
        Map<String, Object> map = service.loadIndex();
        ReturnT<Map> result=new ReturnT(map);
        return result;
    }

    @RequestMapping("/uploadSlide")
    public String upload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request)  {
        try {
            //获取文件名 : file.getOriginalFilename();
            String fileName = file.getOriginalFilename();
            String suffix=fileName.substring(fileName.lastIndexOf("."));
            long s = System.currentTimeMillis();
            fileName="index_"+s+suffix;

            //如果文件名为空，直接回到首页！
            if ("".equals(fileName)){
                return "error";
            }
            System.out.println("上传文件名 : "+fileName);

            //上传路径保存设置
            String path = request.getServletContext().getRealPath("/assets/upload");
            //如果路径不存在，创建一个
            File realPath = new File(path);
            if (!realPath.exists()){
                realPath.mkdir();
            }
            System.out.println("上传文件保存地址："+realPath);

            file.transferTo(new File(realPath +"/"+ fileName));
            String filePathName="assets/upload/"+fileName;
            service.insertSlidePath(filePathName);

            return fileName;
        }catch (Exception e){
            log.debug(e);
            return "error";
        }

    }

}
